package com.ruoyi.web.controller.fee.controller;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.ruoyi.common.core.dto.BillPayStatusDTO;
import com.ruoyi.common.core.dto.PayRequestDTO;
import com.ruoyi.common.core.dto.PayResponseDTO;
import com.ruoyi.common.core.dto.PayStatusDTO;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.fee.domain.PropertyBill;
import com.ruoyi.fee.mapper.PropertyBillMapper;
import com.ruoyi.fee.mapper.PropertyPaymentMapper;
import com.ruoyi.fee.service.PayService;
import com.ruoyi.system.domain.PropertyHouse;
import com.ruoyi.system.mapper.PropertyHouseMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fee.domain.PropertyPayment;
import com.ruoyi.fee.service.IPropertyPaymentService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 缴费记录Controller
 * 
 * @author ruoyi
 * @date 2025-10-27
 */
@Slf4j
@RestController
@RequestMapping("/fee/payment")
public class PropertyPaymentController extends BaseController
{
    @Autowired
    private IPropertyPaymentService propertyPaymentService;

    @Autowired
    private PayService payService;
    /**
     * 查询缴费记录列表
     */
    @PreAuthorize("@ss.hasPermi('fee:payment:list')")
    @GetMapping("/list")
    public TableDataInfo list(PropertyPayment propertyPayment)
    {
        startPage();
        List<PropertyPayment> list = propertyPaymentService.selectPropertyPaymentList(propertyPayment);
        return getDataTable(list);
    }

    /**
     * 导出缴费记录列表
     */
    @PreAuthorize("@ss.hasPermi('fee:payment:export')")
    @Log(title = "缴费记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PropertyPayment propertyPayment)
    {
        List<PropertyPayment> list = propertyPaymentService.selectPropertyPaymentList(propertyPayment);
        ExcelUtil<PropertyPayment> util = new ExcelUtil<PropertyPayment>(PropertyPayment.class);
        util.exportExcel(response, list, "缴费记录数据");
    }

    /**
     * 获取缴费记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('fee:payment:query')")
    @GetMapping(value = "/{paymentId}")
    public AjaxResult getInfo(@PathVariable("paymentId") Long paymentId)
    {
        return success(propertyPaymentService.selectPropertyPaymentByPaymentId(paymentId));
    }

    /**
     * 新增缴费记录
     */
    @PreAuthorize("@ss.hasPermi('fee:payment:add')")
    @Log(title = "缴费记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PropertyPayment propertyPayment)
    {
        return toAjax(propertyPaymentService.insertPropertyPayment(propertyPayment));
    }

    /**
     * 修改缴费记录
     */
    @PreAuthorize("@ss.hasPermi('fee:payment:edit')")
    @Log(title = "缴费记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PropertyPayment propertyPayment)
    {
        return toAjax(propertyPaymentService.updatePropertyPayment(propertyPayment));
    }

    /**
     * 删除缴费记录
     */
    @PreAuthorize("@ss.hasPermi('fee:payment:remove')")
    @Log(title = "缴费记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{paymentIds}")
    public AjaxResult remove(@PathVariable Long[] paymentIds)
    {
        return toAjax(propertyPaymentService.deletePropertyPaymentByPaymentIds(paymentIds));
    }

    /**
     * 创建支付订单
     */
    @PostMapping("/create")
    public AjaxResult createPayOrder(@RequestBody PayRequestDTO request) {
        PayResponseDTO response = payService.createOrder(request);
        return AjaxResult.success(response);
    }

    /**
     * 支付回调接口（供支付平台调用）
     */
    @PostMapping("/notify/wechat")
    public String handleWechatNotify(@RequestBody String notifyData) {
        return payService.handleWechatNotify(notifyData);
    }

    /**
     * 支付回调接口（供支付平台调用）
     */
    @PostMapping("/notify/alipay")
    public String handleAlipayNotify(HttpServletRequest request) {
        return payService.handleAlipayNotify(request);
    }

    /**
     * 查询支付状态
     */
    @GetMapping("/status")
    public AjaxResult queryPayStatus(@RequestParam String outTradeNo) {
        PayStatusDTO status = payService.queryPayStatus(outTradeNo);
        return AjaxResult.success(status);
    }

    /**
     * 关闭订单
     */
    @PostMapping("/close")
    public AjaxResult closePayOrder(@RequestParam String outTradeNo) {
        payService.closeOrder(outTradeNo);
        return AjaxResult.success();
    }

    @Autowired
    private PropertyPaymentMapper paymentMapper;
    @GetMapping("/receipt")
    @PreAuthorize("@ss.hasPermission('property:payment:receipt')")
    public void getReceipt(@RequestParam String receiptNo, HttpServletResponse response) {
        try {
            // 1. 查询收据信息
            PropertyPayment payment = paymentMapper.selectByReceiptNo(receiptNo);
            if (payment == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "收据不存在");
                return;
            }
            // 2. 权限校验（仅订单所属业主或管理员可查看）
            if (!hasReceiptPermission(payment)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "无权限查看");
                return;
            }
            // 3. 生成/返回电子收据（示例：从MinIO获取PDF）
          /*  InputStream in = minioTemplate.getObject("receipt-bucket", receiptNo + ".pdf");
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(receiptNo + ".pdf", "UTF-8"));
            IOUtils.copy(in, response.getOutputStream());*/
        } catch (Exception e) {
            log.error("获取电子收据失败", e);
            throw new ServiceException("获取电子收据失败");
        }
    }
    @Autowired
    private PropertyBillMapper propertyBillMapper;
    @Autowired
    private PropertyHouseMapper propertyHouseMapper;
    // 权限校验逻辑
    private boolean hasReceiptPermission(PropertyPayment payment) {
        Long userId = SecurityUtils.getUserId();
        // 管理员直接通过
        if (SecurityUtils.hasRole("PROPERTY_ADMIN")) {
            return true;
        }
        // 业主需验证是否为账单所属房屋的业主
        PropertyBill bill = propertyBillMapper.selectPropertyBillByBillId(payment.getBillId());
        PropertyHouse house = propertyHouseMapper.selectPropertyHouseByHouseId(bill.getHouseId());
        return house.getOwnerId().equals(userId);
    }
    @GetMapping("/batch/status")
    @PreAuthorize("@ss.hasRole('OWNER') or @ss.hasRole('TENANT')")
    public AjaxResult batchQueryStatus(@RequestParam List<Long> billIds) {
        if (CollectionUtils.isEmpty(billIds)) {
            return AjaxResult.error("账单ID列表不能为空");
        }
        List<BillPayStatusDTO> statusList = payService.batchQueryBillStatus(billIds);
        return AjaxResult.success(statusList);
    }
}
